package com.sadhoc.router;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

import com.sadhoc.router.pdu.HDPacket;

public class ApplicationNotifierThread extends Thread {

	public boolean running = true;
	private OnMessageReceiverI recvr = null;
	private Queue<HDPacket> queue = null;
	
	public ApplicationNotifierThread(OnMessageReceiverI recvr) {
		this.recvr = recvr;
		this.queue = new ConcurrentLinkedQueue<HDPacket>();
	}
	
	/* 
	 * This runs indefinately to push HDPackets up to onMsgReceiver
	 */
	public void run() {
		
		while (running) {
			try {
				synchronized(queue) {
					while (queue.isEmpty()) {
						queue.wait();
					}
				}
				recvr.onMessageRecv(queue.poll());
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
	}
	
	/*
	 * Adds a new HDPacket to push up to the application
	 */
	public void add(HDPacket hdp) {
		
		queue.add(hdp);
		synchronized (queue) {
			queue.notify();
		}
		
	}
	
}
